import Vue from 'vue';
import VueRouter from 'vue-router';
import { getItem, removeItem } from '@/utils/cookieUtil';
import store from '@/store';
import { Message } from 'element-ui';
// import { reqUser } from '@/api/user';

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}


/**
 * 静态路由
 */
export const constantRouterMap = [
	{
		path: '/',
		redirect: '/home',
		hidden: true,
	},
	// {
	// 	path: '/login',
	// 	meta: {
	// 		icon: null,
	// 		title: null,
	// 	},
	// 	hidden: true,
	// 	sort: null,
	// 	component: () => import('@/views/login'),
	// },
	{
		path: '/home',
		name: 'Home',
		meta: {
			icon: null,
			title: '首页',
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/home/Home.vue'),
	},
    {
		path: '/job/intern',
		name: 'Job',
		meta: {
			icon: null,
			title: '职位列表',
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/job/JobIntern.vue'),
	},
	{
		path: '/job/formal',
		name: 'Job',
		meta: {
			icon: null,
			title: '职位列表',
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/job/JobFormal.vue'),
	},
    {
		path: '/admin',
		name: 'Admin',
		meta: {
			icon: null,
			title: '管理后台',
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/admin/Admin.vue'),
		redirect: '/admin/user',
		children: [
			{
				path: 'user',
				name: 'UserManagement',
				meta: {
					icon: null,
					title: '用户管理',
				},
				hidden: true,
				sort: null,
				component: () => import('@/views/admin/UserManagement.vue'),
			},
			{
				path: 'job',
				name: 'JobManagement',
				meta: {
					icon: null,
					title: '职位管理',
				},
				hidden: true,
				sort: null,
				component: () => import('@/views/admin/JobManagement.vue'),
			},
			{
				path: 'company',
				component: () => import('@/views/admin/CompanyManagement.vue'),
				meta: { title: '公司管理', hidden: true }
			},
			{
				path: 'deliver',
				component: () => import('@/views/admin/DeliverManagement.vue'),
				meta: { title: '投递管理', hidden: true }
			},
			{
				path: 'job-examine',
				component: () => import('@/views/admin/JobAudit.vue'),
				meta: { title: '职位审核', hidden: true }
			},
			{
				path: 'notice',
				component: () => import('@/views/admin/NoticeAdmin.vue'),
				meta: { title: '公告管理', hidden: true }
			}
		]
	},
	{
		path: '/user',
		name: 'User',
		meta: {
			icon: null,
			title: '职位列表',
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/user/User.vue'),
	},

]
/**
 * 动态路由
 */
export const asyncRouterMap = [


]


const router = new VueRouter({
	mode: "history",
	routes: constantRouterMap,
	// // 控制路由跳转滚动条的位置为最顶部
	scrollBehavior(to, from, savedPosition) {
		// 始终滚动到顶部，y代表距离顶部的距离
		return { y: 0 }
	},
})

// const whiteList = ['/login', '/file/share/'] // 不重定向白名单

// router.beforeEach((to, from, next) => {
// 	if (getItem("token")) {
// 		if (store.state.user.userInfo == null) {
// 			// 拉取用户信息
// 			getUserInfo(next);
// 		}
// 		if (to.path.match('/backend/admin') && store.state.user.roleList.length === 1) {
// 			next({ path: '/' })
// 		}
// 		next()
// 	} else {
// 		next();
// 		// if (to.path == '/login') {
// 		// 	next()
// 		// } else {
// 		// 	next("/login")
// 		// }
// 	}
// 	next()
// })

router.beforeEach((to, from, next) => {
	// if (getItem("token")) {
	// 	if (store.state.user.userInfo == null) {
	// 		// 拉取用户信息  
	// 		getUserInfo(next).then(() => {
	// 			if (to.path.match('/backend/admin') && store.state.user.roleList.length === 1) {
	// 				next({ path: '/' })
	// 			} else if (to.path == '/login') {
	// 				next({ path: '/' })
	// 			} else {
	// 				next();
	// 			}
	// 		}).catch((error) => {
	// 			next({ path: '/' })
	// 		});
	// 	} else {
	// 		if (to.path.match('/backend/admin') && store.state.user.roleList.length === 1) {
	// 			next({ path: '/' })
	// 		} else {
	// 			next();
	// 		}
	// 	}
	// } else {
	// 	if (to.path == '/usersapce') {
	// 		next();
	// 	} else {
	// 		next();
	// 	}
	// }
	next()
})

router.afterEach(() => {

});

function getUserInfo(next) {
	return new Promise((resolve, reject) => {
		reqUser({
			menus: JSON.parse(localStorage.getItem("menus")),
			permissions: JSON.parse(localStorage.getItem("permissions")),
			roles: JSON.parse(localStorage.getItem("roles"))
		}).then(res => {
			store.dispatch('setUserInfo', res.data)
				.then(() => {
					return store.dispatch('generateRoutes', JSON.parse(localStorage.getItem('menus')));
				})
				.then(() => {
					// 动态添加可访问路由表  
					router.addRoutes(store.state.menu.addRouters);
					resolve();
				})
				.catch((error) => {
					console.error('处理流程出错:', error);
					// 处理错误，例如跳转到错误页面或重新登录
					next({ path: '/' })
				});
		}).catch(error => {
			next({ path: '/' })
			Message.error({
				message: error.msg
			});
			removeItem("token");
			removeItem("permissions");
			removeItem("menus");
			removeItem("roles");


			// if (error.code == 500 && error.msg == '身份解析失败') {
			// 	removeItem("token");
			// 	Message.error({
			// 		message: "身份过期，请重新登录"
			// 	});
			// } else {
			// 	Message.error({
			// 		message: error.msg
			// 	});
			// }
		})
	});
}




export default router